import React, { useEffect, useState } from 'react';
import { Button, Cascader, Col, Form, Input, message, Row, Select, Space } from 'antd';
import axios from 'axios';
import { GLOBAL_SELECTIONS, TALENT_INSERT, TEL_EXIST, } from 'src/constants/api-constants';
// import { UploadFile } from 'antd/lib/upload/interface';
import provice from '../../../../util/place';

const { Option } = Select;
const options = provice;

interface DetailProps {
  setInsertFalse: Function;
  getList: Function;
  setPage: Function;
}

const Insert: React.FC<DetailProps> = props => {
  const { setInsertFalse, getList, setPage } = props;
  const [educationOptions, setEducationOptions] = useState([]);
  const [applicationAreaOptions, setApplicationAreaOptions] = useState([]);
  const [talentTypeOptions, setTalentTypeOptions] = useState([]);
  const [organizationTypeOptions, setOrganizationTypeOptions] = useState<any>(
    []
  );
  const [titleTypeOptions, setTitleTypeOptions] = useState<any>([]);
  const [positionTypeOptions, setPositionTypeOptions] = useState<any>([]);
  // const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [today, setToday] = useState('');
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const formLayout = {
    labelCol: {
      span: 9,
    },
    wrapperCol: {
      span: 12,
    },
  };
  const formItemLayout1 = {
    labelCol: {
      span: 3,
    },
    wrapperCol: {
      span: 20,
    },
  };
  const formItemLayout2 = {
    labelCol: {
      span: 3,
    },
    wrapperCol: {
      span: 21,
    },
  };

  /*   const uploadProps = {
      onRemove: (_file: UploadFile) => {
        setFileList([]);
      },
      beforeUpload: (file: UploadFile) => {
        setFileList([file]);
        return false;
      },
      fileList,
      accept: '.pdf',
    }; */

  const clearForm = () => {
    form.resetFields();
    // setFileList([]);
  };

  const submit = (e: {
    applicationArea: string | Blob;
    description: string | Blob;
    education: string | Blob;
    email: string | Blob;
    addressBefore: any[];
    address: string;
    filler: string | Blob;
    name: string | Blob;
    position: string | Blob;
    unit: string | Blob;
    title: string | Blob;
    type: string | Blob;
    sex: string | Blob;
    age: string | Blob;
    talentType: string | Blob;
    tel: string | Blob;
    file: { file: string | Blob };
  }) => {
    const formData = new FormData();
    formData.append('applicationArea', e.applicationArea);
    formData.append('description', e.description);
    formData.append('education', e.education);
    if (e.email) formData.append('email', e.email);
    let add = e.addressBefore.join(';');
    if (e.address) add += `;${e.address}`;
    formData.append('address', add);
    formData.append('filler', e.filler);
    formData.append('name', e.name);
    if (e.position) formData.append('position', e.position);
    formData.append('unit', e.unit ?? '');
    if (e.title) formData.append('title', e.title);
    if (e.type) formData.append('type', e.type);
    formData.append('sex', e.sex);
    if (e.age) formData.append('age', e.age);
    formData.append('talentType', e.talentType);
    formData.append('tel', e.tel);
    formData.append('file', e.file ? e.file.file : new File([], 'null.pdf'));

    axios
      .post(TALENT_INSERT, formData)
      .then(r => {
        if (r.data.mainData.exist !== true) {
          message.info('提交成功');
        } else {
          message.error(r.data.msg);
        }
      })
      .catch(e => {
        message.error('提交失败');
        console.log(e);
      })
      .finally(() => {
        setPage(1);
        getList();
        clearForm();
        setInsertFalse();
      });
    setLoading(false);
  };

  useEffect(() => {
    const today = new Date();
    const now =
      today.getFullYear() +
      '-' +
      (today.getMonth() + 1) +
      '-' +
      today.getDate();
    setToday(now);

    axios
      .get(GLOBAL_SELECTIONS)
      .then(r => {
        const { mainData } = r.data;

        const applicationAreaOptions = mainData.applicationArea.map(
          (item: any) => {
            return (
              <Option key={item.uuid} value={item.uuid}>
                {item.name}
              </Option>
            );
          }
        );

        const organizationsTypeOptions = mainData.organizationType.map(
          (item: any) => {
            return (
              <Option key={item.uuid} value={item.uuid}>
                {item.name}
              </Option>
            );
          }
        );

        const talentTypeOptions = mainData.talentType.map((item: any) => {
          return (
            <Option key={item.uuid} value={item.uuid}>
              {item.typeName}
            </Option>
          );
        });

        const educationOptions = mainData.education.map((item: any) => {
          return (
            <Option key={item} value={item}>
              {item}
            </Option>
          );
        });

        const titleOptions = mainData.titleType.map((item: any) => {
          return (
            <Option key={item.uuid} value={item.uuid}>
              {item.name}
            </Option>
          );
        });

        const positionOptions = mainData.positionType.map((item: any) => {
          return (
            <Option key={item.uuid} value={item.uuid}>
              {item.name}
            </Option>
          );
        });

        setApplicationAreaOptions(applicationAreaOptions);
        setOrganizationTypeOptions(organizationsTypeOptions);
        setTalentTypeOptions(talentTypeOptions);
        setEducationOptions(educationOptions);
        setTitleTypeOptions(titleOptions);
        setPositionTypeOptions(positionOptions);
      })
      .catch(e => {
        console.log(e);
      });
  }, []);

  return (
    <Form
      layout="horizontal"
      labelAlign="right"
      {...formLayout}
      colon={true}
      form={form}
      onFinish={(values) => {
        setLoading(true);
        submit(values);
      }}
    >
      <Row justify="space-between">
        <Col span={6}>
          <Form.Item
            label="姓名"
            name="name"
            rules={[{ required: true, message: '姓名不能为空' }]}
          >
            <Input />
          </Form.Item>
        </Col>
        <Col span={6}>
          <Form.Item
            label="性别"
            name="sex"
            rules={[{ required: true, message: '性别不能为空' }]}
          >
            <Select>
              <Option value={1}>男</Option>
              <Option value={0}>女</Option>
            </Select>
          </Form.Item>
        </Col>
        <Col span={6}>
          <Form.Item
            label="年龄"
            name="age"
          // rules={[{ required: true, message: '年龄不能为空' }]}
          >
            <Input type="number" max={100} min={0} step={1} />
          </Form.Item>
        </Col>
      </Row>
      <Row justify="space-between">
        <Col span={18}>
          <Form.Item
            label="工作单位"
            name="unit"
            {...formItemLayout1}
          // rules={[{ required: true, message: '工作单位不能为空' }]}
          >
            <Input />
          </Form.Item>
        </Col>
        <Col span={6}>
          <Form.Item
            label="单位性质"
            // rules={[{ required: true, message: '单位性质不能为空' }]}
            name="type"
          >
            <Select>{organizationTypeOptions}</Select>
          </Form.Item>
        </Col>
      </Row>
      <Row justify="space-between">
        <Col span={6}>
          <Form.Item
            label="职称"
            name="title"
            rules={[{ required: true, message: '职称不能为空' }]}
          >
            <Select>{titleTypeOptions}</Select>
          </Form.Item>
        </Col>
        <Col span={6}>
          <Form.Item
            label="职务"
            name="position"
          // rules={[{ required: true, message: '岗位不能为空' }]}
          >
            <Select>{positionTypeOptions}</Select>
          </Form.Item>
        </Col>
        <Col span={6}>
          <Form.Item
            label="行业领域"
            name="applicationArea"
            rules={[{ required: true, message: '行业领域不能为空' }]}
          >
            <Select>{applicationAreaOptions}</Select>
          </Form.Item>
        </Col>
      </Row>
      <Row justify="space-between">
        <Col span={6}>
          <Form.Item
            label="人才类型"
            name="talentType"
            rules={[{ required: true, message: '人才类型不能为空' }]}
          >
            <Select>{talentTypeOptions}</Select>
          </Form.Item>
        </Col>
        <Col span={6}>
          <Form.Item
            label="学历"
            name="education"
            rules={[{ required: true, message: '学历不能为空' }]}
          >
            <Select>{educationOptions}</Select>
          </Form.Item>
        </Col>
        <Col span={6}>
          <Form.Item
            label="电话"
            name="tel"
            rules={[
              {
                validator: (_, value) => {
                  // if (value.length === 0 || !value) {
                  //   return Promise.reject(new Error('电话不能为空'));
                  // }
                  const pat =
                    /^(((\(\d{3,4}\)|\d{3,4})?\d{7,8})|(1[3-9][0-9]{9}))$/;

                  if (!pat.test(value)) {
                    return Promise.reject(new Error('电话格式不正确'));
                  }

                  if (
                    value.length === 7 ||
                    value.length === 8 ||
                    value.length === 11
                  ) {
                    return axios.post(TEL_EXIST, { tel: value })
                      .then(res => {
                        console.log(value);

                        console.log(res);
                        if (res.data.mainData) {
                          return Promise.reject(new Error('电话号码已被注册'));
                        }
                        return Promise.resolve();
                      });
                  }
                },
              },
            ]}
          >
            <Input />
          </Form.Item>
        </Col>
        <Col span={6}>
          <Form.Item
            label="E-Mail"
            name="email"
            rules={[
              {
                type: 'email',
                message: '邮箱格式不正确',
              },
              // { required: true, message: 'email不能为空' },
            ]}
          >
            <Input />
          </Form.Item>
        </Col>
      </Row>
      <Row justify="space-between">
        <Col span={6}>
          <Form.Item
            name="addressBefore"
            label="居住城市"
            rules={[{ required: true, message: '城市不能为空' }]}
          >
            <Cascader options={options} placeholder="请输入居住的城市" />
          </Form.Item>
        </Col>
        <Col span={18}>
          <Form.Item
            label="具体街道"
            name="address"
          // rules={[{ required: true, message: '街道不能为空！' }]}
          >
            <Input />
          </Form.Item>
        </Col>
      </Row>
      <Row style={{ width: '100%' }}>
        <Col span={18}>
          <Form.Item
            name="description"
            label="人才简历"
            {...formItemLayout2}
            rules={[{ required: true, message: '人才简历不能为空' }]}
          >
            <Input.TextArea
              maxLength={300}
              rows={4}
              style={{ resize: 'none' }}
            />
          </Form.Item>
        </Col>
      </Row>
      {/*<Row style={{ width: '100%' }}>*/}
      {/*  <Col span={18}>*/}
      {/*    <Form.Item label="附件材料" name="file" {...formItemLayout1}>*/}
      {/*      <Upload {...uploadProps}>*/}
      {/*        <Button type="primary" icon={<UploadOutlined/>}>*/}
      {/*          添加附件(PDF格式)*/}
      {/*        </Button>*/}
      {/*      </Upload>*/}
      {/*    </Form.Item>*/}
      {/*  </Col>*/}
      {/*</Row>*/}
      <Row style={{ width: '100%', marginTop: '10vh' }} align="bottom">
        <Col span={6}>
          <Form.Item label="录入时间">
            <Input disabled value={today} />
          </Form.Item>
        </Col>
        <Col span={6}>
          <Form.Item
            label="填写人"
            name="filler"
            rules={[{ required: true, message: '填写人不能为空' }]}
            initialValue={localStorage.getItem('userName')}
          >
            <Input readOnly />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item wrapperCol={{ span: 22 }}>
            <Space style={{ float: 'right' }}>
              <Button
                type="primary"
                htmlType="submit"
                loading={loading}
              /* onClick={() => {
                submit(values);
                console.log('called...');
                const values = form.getFieldsValue();
                let error = false;

                form.validateFields();

                for (let value in values) {
                  if (values.hasOwnProperty(value)) {
                    console.log(values[value]);
                    if (
                      (!values[value] || values[value] === '') &&
                      value !== 'file'
                    ) {
                      error = true;
                      break;
                    }
                  }
                }
                console.log(values);

                console.log('errpr:', error);

                if (!error) {
                  submit(values);
                }
                setLoading(false);
              }} */
              >
                确认
              </Button>
              <Button
                type="primary"
                onClick={() => {
                  setInsertFalse();
                  clearForm();
                }}
              >
                返回
              </Button>
            </Space>
          </Form.Item>
        </Col>
      </Row>
    </Form>
  );
};

export default Insert;
